/**
 * 时间: 2024年10月12日 15点32分
 * 测量工具类
 */


import * as Cesium from "cesium";

/**
 * @description 测量距离
 */
export class MeasureDistance {
  constructor(viewer,cesium,cesiumHandler) {
    this.viewer = viewer;
    this.cesium = cesium;
    this.cesiumHandler = cesiumHandler;
    this.positions = [];
    this.totalDistance = 0;
    this.polyline=null;
    //创建一个新的标签用于显示距离
    this.distanceLabel = viewer.entities.add({
      label: {
        show: false,
        showBackground: true,
        font: '14px monospace',
        horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
        pixelOffset: new Cesium.Cartesian2(15, 0)
      }
    });
  }
  // 创建一个标签用于显示距离
  //开始测量
  start(){
    // 鼠标点击事件，记录点并计算距离
    this.cesiumHandler.setInputAction( (movement)=>{
      const cartesian = this.viewer.scene.pickPosition(movement.position);

      if (Cesium.defined(cartesian)) {
        // 添加点到数组
        this.positions.push(cartesian);

        // 如果已经有点，计算距离
        if (this.positions.length > 1) {
          var point1 = this.positions[this.positions.length - 2];
          var point2 = this.positions[this.positions.length - 1];
          var distance = Cesium.Cartesian3.distance(point1, point2);

          this.totalDistance += distance;

          // 更新线条（多段线）
          if (!Cesium.defined(this.polyline)) {
            this.polyline = this.viewer.entities.add({
              polyline: {
                positions: this.positions,
                width: 3,
                material: Cesium.Color.YELLOW
              }
            });
          } else {
            this.polyline.polyline.positions = this.positions;
          }

          // 显示距离标签
          this.distanceLabel.position = point2;
          this.distanceLabel.label.show = true;
          this.distanceLabel.label.text = '总距离: ' + (this.totalDistance / 1000).toFixed(2) + ' km'; // 单位换算为公里
        }
      }
    }, Cesium.ScreenSpaceEventType.LEFT_DOWN);

    //创建取消事件
    // 右击事件停止测量
    this.cesiumHandler.setInputAction(function () {
      this.cesiumHandler.removeInputAction(this.Cesium.ScreenSpaceEventType.LEFT_DOWN);
      this.cesiumHandler.removeInputAction(this.Cesium.ScreenSpaceEventType.RIGHT_CLICK);
      this.distanceLabel.label.show = false;  // 停止时隐藏标签
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
  }
}
